﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace Pipes.Queries.Model.Query
{
  public class NumericLiteral : IExpression
  {
    private int _origScale = 0;
    private decimal _value = 0;

    public bool Deterministic { get { return true; } }
    public MetaData.GeneralDataType InferredType { get; set; }
    public decimal Value {
      get
      {
        return _value;
      }
    }

    public NumericLiteral() 
    {
      this.InferredType = MetaData.GeneralDataType.numeric;
    }
    public NumericLiteral(string value) : this()
    {
      _value = decimal.Parse(value);
      var decIndex = value.IndexOf('.');
      if (decIndex >= 0)
      {
        _origScale = value.Length - decIndex - 1;
      }
    }
    public NumericLiteral(int value) : this()
    {
      _value = value;
      _origScale = 0;
    }
    public void Negate()
    {
      _value *= -1;
    }

    public override string ToString()
    {
      return this.Value.ToString("f" + _origScale.ToString());
    }

    public void Visit(Parser.IQueryVisitor visitor)
    {
      visitor.Visit(this);
    }

    public object Evaluate()
    {
      return this._value;
    }

    public static implicit operator decimal(NumericLiteral x)
    {
      return x.Value;
    }
    public static implicit operator NumericLiteral(decimal x)
    {
      return new NumericLiteral(x.ToString("r"));
    }
    public static implicit operator bool(NumericLiteral x)
    {
      return Math.Round(x.Value, 25) != 0;
    }
    public static implicit operator NumericLiteral(bool x)
    {
      return new NumericLiteral((x ? 1 : 0));
    }
  }
}
